package com.liuyan.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.liuyan.pojo.Content;
import com.liuyan.service.IContentService;
import com.liuyan.util.BaseController;
import com.liuyan.util.CommonConstants;
import com.liuyan.util.MD5;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.liuyan.pojo.User;
import com.liuyan.service.IUserService;

import java.util.List;

@Controller
@RequestMapping("userLoginController")
public class UserController extends BaseController{
    @Resource
    private IUserService userService;

    @Resource
    private IContentService contentService;
    private static Logger log = Logger.getLogger(UserController.class);
    /**
     * 用户登录
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(params = "method=login")
    public String login(HttpServletRequest request, HttpServletResponse response) {
        String userName = request.getParameter("username");
        String password = MD5.sign(request.getParameter("userpwd"),"", CommonConstants.SYSTEMTYPE);
        try{
            boolean isPass = this.userService.getUserPass(userName,password);
            if(isPass){
                User user = this.userService.getUser(userName);
                HttpSession session = request.getSession();//将id存到session中
                session.setAttribute("userId",user.getId());


                session.setAttribute("flag","0");// 设置一个标识，当退出时，值变成"1"
                writeText(response,CommonConstants.RESULT_SUCCESS);
            }else {
                writeText(response,CommonConstants.RESULT_FAIL);
            }
        }catch (Exception e){
            log.error("登陆失败"+e.toString());
            writeText(response, "登录失败！原因:"+e.getMessage());
        }

        return null;
    }
    /**
     * 更改头像
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(params = "method=alterHead")
    public String alterHead(HttpServletRequest request, HttpServletResponse response,Model model) {
        HttpSession session = request.getSession();//将id存到session中
        Object obj  = session.getAttribute("userId");
        if(obj!=null) {
            int userId = Integer.parseInt(session.getAttribute("userId").toString());
            User user = new User();
            int headId = Integer.parseInt(request.getParameter("headId"));
            user.setHead(headId);
            user.setId(userId);
            boolean isSuccess = this.userService.modifyHead(user);
            if (isSuccess) {
                writeText(response, CommonConstants.RESULT_SUCCESS);
            } else {
                writeText(response, CommonConstants.RESULT_FAIL);
            }
        }else {
            model.addAttribute("message","noLogin");
            return "login";
        }
        return null;
    }
    @RequestMapping(params = "method=loginSuccess")
    public String loginSuccess(HttpServletRequest request, Model model) {

        HttpSession session = request.getSession();
        Object obj  = session.getAttribute("userId");
        if(obj!=null) {
            List<User> userlist = this.userService.getUserList();
            List<Content> contentListForLevelOne = this.contentService.contentListForLevelOne();

            /*先查找User的list，在查找content的list1，遍历content的list2，如果list2中bean中的userid等于list1中bean的id，那么就把list1中的bean的head赋值给list2中的bean的head*/
            for (int j = 0; j < contentListForLevelOne.size(); j++) {
                for(int i=0;i<userlist.size();i++) {
                    if(userlist.get(i).getId()==contentListForLevelOne.get(j).getUserId()){
                        contentListForLevelOne.get(j).setHead(userlist.get(i).getHead());
                    }
                }
            }
            List<Content> contentListForLevelTwo = this.contentService.contentListForLevelTwo();
            for (int j = 0; j < contentListForLevelTwo.size(); j++) {
                for(int i=0;i<userlist.size();i++) {
                    if(userlist.get(i).getId()==contentListForLevelTwo.get(j).getUserId()){
                        contentListForLevelTwo.get(j).setHead(userlist.get(i).getHead());
                    }
                }
            }
            model.addAttribute("contentListForLevelOne",contentListForLevelOne);
            model.addAttribute("contentListForLevelTwo",contentListForLevelTwo);
            int count = this.contentService.getAllCount();//获得总数量 ，好进行分页

            model.addAttribute("count",count);
            model.addAttribute("userId",Integer.parseInt(session.getAttribute("userId").toString()));
            model.addAttribute("currentPage",1);
            return "index";
        }else {
            model.addAttribute("message","noLogin");
            return "login";
        }
    }


    /**
     * 用户注册
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(params = "method=register")
    public String register(HttpServletRequest request, HttpServletResponse response) {
        String userName = request.getParameter("user");
        String password = MD5.sign(request.getParameter("passwd"),"", CommonConstants.SYSTEMTYPE);
        try {
            boolean isHave = this.userService.isHave(userName);
            if (isHave) {
                writeText(response, CommonConstants.RESULT_EXIST);
            } else {
                User user = new User();
                user.setPassword(password);
                user.setUserName(userName);
                boolean isSuccess = this.userService.addUser(user);
                if (isSuccess) {
                    writeText(response, CommonConstants.RESULT_SUCCESS);
                } else {
                    writeText(response, CommonConstants.RESULT_FAIL);
                }
            }
        }catch (Exception e){
            log.error("注册失败:"+e.toString());
            writeText(response,"注册失败！原因:"+e.getMessage());
        }
        return null;

    }


}